package com.weitu.securitycheck.controller;

import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.permission.department.service.DepartmentService;
import com.weitu.permission.user.entity.User;
import com.weitu.permission.user.service.UserService;
import com.weitu.plugin.PageView;
import com.weitu.securitycheck.entity.CheckProblem;
import com.weitu.securitycheck.entity.CheckRecord;
import com.weitu.securitycheck.entity.CheckRecordCriteria;
import com.weitu.securitycheck.service.CheckProblemService;
import com.weitu.securitycheck.service.CheckRecordService;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/5/20
 */
@Controller
@RequestMapping(value = "securityCheck/checkRecord")
public class CheckRecordController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "securityCheck/checkRecord";
    private final CheckRecordService checkRecordService;
    private final CheckProblemService checkProblemService;
    private final UserService userService;
    private final DepartmentService departmentService;
    private final DataAuthorityService dataAuthorityService;

    @Autowired
    public CheckRecordController(CheckRecordService checkRecordService
            , CheckProblemService checkProblemService
            , UserService userService
            , DepartmentService departmentService
            , DataAuthorityService dataAuthorityService) {
        this.checkRecordService = checkRecordService;
        this.checkProblemService = checkProblemService;
        this.userService = userService;
        this.departmentService = departmentService;
        this.dataAuthorityService = dataAuthorityService;
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        CheckRecordCriteria criteria = new CheckRecordCriteria();
        CheckRecordCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0);
        putSearchCriteria(cr);

        int count = checkRecordService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<CheckRecord> checkRecords = checkRecordService.selectByCriteria(criteria);
        return dataGridPagination.flushDataGridData(checkRecords);
    }

    @ResponseBody
    @RequestMapping(value = "generate", method = RequestMethod.POST)
    public AjaxResult generateAjax() throws Exception {
        List<CheckProblem> checkProblems = checkProblemService.selectByNotInRecord();
        if (checkProblems.size() > 0) {
            List<CheckRecord> checkRecords = mapCheckProblemsToCheckRecords(checkProblems);
            if (checkRecordService.insertBatch(checkRecords)) {
                return success("台账生成成功！");
            }
            return fail("台账生成失败！");
        }
        return fail("没有需要生成的数据！");
    }

    private List<CheckRecord> mapCheckProblemsToCheckRecords(List<CheckProblem> checkProblems) {
        List<CheckRecord> checkRecords = new ArrayList<CheckRecord>();
        for (CheckProblem checkProblem : checkProblems) {
            CheckRecord checkRecord = new CheckRecord();
            String id = IDGenerator.getId();
            checkRecord.setId(id);
            checkRecord.setAddUserId(getSessionUser().getId());
            checkRecord.setAddDeptId(getSessionUser().getDepartment().getId());
            checkRecord.setAddTime(DateTimeUtil.formatterDateTime());
            checkRecord.setRemarks(checkProblem.getRemarks());
            checkRecord.setCheckDeptIds(checkProblem.getCheckInfo().getCheckDeptIds());
            checkRecord.setCheckDeptNames(getCheckDeptNamesByIds(checkProblem.getCheckInfo().getCheckDeptIds()));
            checkRecord.setCheckUserIds(checkProblem.getCheckInfo().getCheckUserIds());
            checkRecord.setCheckUserNames(getCheckUserNamesByIds(checkProblem.getCheckInfo().getCheckUserIds()));
            checkRecord.setCheckStartDate(checkProblem.getCheckInfo().getCheckStartDate());
            checkRecord.setCheckEndDate(checkProblem.getCheckInfo().getCheckEndDate());
            checkRecord.setCheckTypeId(checkProblem.getCheckInfo().getCheckTypeId());
            checkRecord.setCheckTypeName(checkProblem.getCheckInfo().getCheckTypeName());
            checkRecord.setCheckDate(checkProblem.getCheckDate());
            checkRecord.setReceiveDeptIds(checkProblem.getReceiveDeptIds());
            checkRecord.setReceiveDeptNames(checkProblem.getReceiveDeptNames());
            checkRecord.setContractorAuditId(checkProblem.getContractorAuditId());
            checkRecord.setContractorAuditName(checkProblem.getContractorAuditName());
            checkRecord.setRectifyRemarks(checkProblem.getRectifyRemarks());
            // TODO: 2017/5/20 立即整改时整改期限为检查当天
            checkRecord.setRectifyLimitDate(checkProblem.getCheckDate());
            checkRecord.setAuditState(checkProblem.getAuditState());
            // TODO: 2017/5/20 以下整改情况为整改完成时填写，到时获取
            checkRecord.setRectifyDescribe(checkProblem.getRectifyRemarks());
            checkRecord.setRectifyCompleteDate(checkProblem.getCheckDate());
            checkRecord.setRectifyAccepterIds(checkProblem.getCheckInfo().getCheckUserIds());
            checkRecord.setRectifyAccepterNames(checkProblem.getCheckInfo().getCheckUserNames());
            checkRecord.setCheckProblemId(checkProblem.getId());
            checkRecords.add(checkRecord);
        }
        return checkRecords;
    }

    /**
     * 根据检查人id逗号分隔字符串设置相关名称的值
     *
     * @param ids id字符串集合
     */
    private String getCheckUserNamesByIds(String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            String[] idArray = ids.split(",");
            List<User> users = userService.selectUsersByIds(idArray);
            StringBuilder sb = new StringBuilder();
            for (User user : users) {
                String userName = user.getRealName();
                sb.append(",").append(userName);
            }
            return sb.substring(1);
        } else
            return null;
    }

    /**
     * 根据检查部门id逗号分隔字符串设置相关名称的值
     *
     * @param ids id字符串集合
     */
    private String getCheckDeptNamesByIds(String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            String[] idArray = ids.split(",");
            return StringUtils.join(departmentService.selectNamesByIds(Arrays.asList(idArray)), ',');
        } else
            return null;
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(CheckRecordCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("checkTypeId"))) {
            criteria.andCheckTypeIdEqualTo(getPara("checkTypeId"));
        }
        if (StringUtils.isNotEmpty(getPara("checkDeptId"))) {
            criteria.andCheckDeptIdsLike("%" + getPara("checkDeptId") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("checkUserId"))) {
            criteria.andCheckUserIdsLike("%" + getPara("checkUserId") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("checkStartDate"))) {
            criteria.andCheckStartDateEqualTo(getPara("checkStartDate"));
        }
        if (StringUtils.isNotEmpty(getPara("checkEndDate"))) {
            criteria.andCheckEndDateEqualTo(getPara("checkEndDate"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }
}
